// 命令接口，定义了执行命令的方法   
interface Command {
    void execute();   
}
   
// 灯光类，作为接收者，具有开灯和关灯的方法   
class Light {
    public void turnOn() {
        System.out.println("The light is on.");
    }

    public void turnOff() {
        System.out.println("The light is off.");
    }   
}
   
// 打开灯光的命令类，实现命令接口，关联灯光对象   
class LightOnCommand implements Command {
    private final Light light;

    public LightOnCommand(Light light) {
        this.light = light;
    }

    @Override
    public void execute() {
        light.turnOn();
    }   
}
   
// 关闭灯光的命令类，实现命令接口，关联灯光对象   
class LightOffCommand implements Command {
    private final Light light;

    public LightOffCommand(Light light) {
        this.light = light;
    }

    @Override
    public void execute() {
        light.turnOff();
    }   
}
   
// 开关类，作为调用者，可设置命令并执行   
class Switch {
    private Command command;

    public void setCommand(Command command) {
        this.command = command;
    }

    public void executeCommand() {
        if (command!= null) {
            command.execute();
        }
    }   
}
   
// 测试命令模式的主类   
public class CommandPatternDemo {
    public static void main(String[] args) {
        // 实例化灯光对象
        Light light = new Light();

        // 创建打开灯光和关闭灯光的命令对象
        LightOnCommand lightOnCommand = new LightOnCommand(light);
        LightOffCommand lightOffCommand = new LightOffCommand(light);

        // 创建开关对象
        Switch switchControl = new Switch();

        // 执行打开灯光的操作
        switchControl.setCommand(lightOnCommand);
        switchControl.executeCommand();

        // 执行关闭灯光的操作
        switchControl.setCommand(lightOffCommand);
        switchControl.executeCommand();
    }   
}


